package com.ec.auth.controller;

import com.ec.auth.authen.IAuthen;
import com.ec.auth.authen.UserAuthenBuilder;
import com.ec.common.constant.RedisKeyConstant;
import com.ec.auth.dto.UserLoginDTO;
import com.ec.core.common.core.api.ResponseMsg;
import com.ec.core.common.core.api.Result;
import com.ec.core.common.core.secure.AuthInfo;
import com.ec.core.common.utils.CoreRandomUtil;
import com.ec.core.redis.utils.CoreRedisUtil;
import com.wf.captcha.ArithmeticCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * 授权认证接口
 *
 * @author: Eric Lee
 * @time: 2021/5/24 16:36
 */
@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {
    /**
     * 登录
     *
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/token")
    public Result<AuthInfo> token(@Validated @RequestBody UserLoginDTO userLoginDTO) {
        IAuthen authenType = UserAuthenBuilder.getGrantType(userLoginDTO.getGrantType());
        AuthInfo authInfo = authenType.authentication(userLoginDTO);
        return ResponseMsg.success(authInfo);
    }

    /**
     * 获取验证码
     *
     * @return
     */
    @GetMapping("/captcha")
    public Result<Object> captcha() {
        // 英文+数字
//        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
//        String verCode = specCaptcha.text().toLowerCase();
        //计算
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
        captcha.setLen(2);
        captcha.getArithmeticString();
        String verCode = captcha.text().toLowerCase();
        String key = CoreRandomUtil.randomUUID(true, true);
        // 存入redis并设置过期时间为60秒
        CoreRedisUtil.set(String.format(RedisKeyConstant.UserLogin.CAPTCHA_KEY, key), verCode, 60, TimeUnit.SECONDS);
        Map<String, String> map = new HashMap(2);
        map.put("codeKey", key);
        map.put("image", captcha.toBase64());
        return ResponseMsg.success(map);
    }

}
